package org.qiuqiu.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.qiuqiu.pojo.User;
import org.qiuqiu.tools.*;

/**
 * @author 杜秋野
 * 
 */
public class UserDao {

	/**
	 * 该方法将插入新的用户资料
	 * 
	 * @param user
	 * @return
	 * @throws SQLException
	 */
	public int insert(User user) throws SQLException {
		int userId = 0;
		try {
			SqlMapTool.getSqlMap().startTransaction();
			userId = (Integer) SqlMapTool.getSqlMap()
					.insert("insertUser", user);
			SqlMapTool.getSqlMap().commitTransaction();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			SqlMapTool.getSqlMap().endTransaction();
		}
		return userId;
	}

	/**
	 * 获得指定用户的详细信息
	 * 
	 * @param userId
	 * @return
	 * @throws SQLException
	 */
	public List<User> getUser(int userId) throws SQLException {
		List<User> list = new ArrayList<User>();
		list = SqlMapTool.getSqlMap().queryForList("getUserById", userId);
		return list;
	}

	public User checkUserPassword(String userName) {
		User user = null;
		try {
			user = (User) SqlMapTool.getSqlMap().queryForObject(
					"getUserByUserName", userName);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}

	/**
	 * 修改指定用户的信息
	 * 
	 * @param user
	 * @return
	 * @throws SQLException
	 */
	public boolean modUser(User user) throws SQLException {
		boolean result = false;
		try {
			SqlMapTool.getSqlMap().startTransaction();
			SqlMapTool.getSqlMap().update("updateUser", user);
			SqlMapTool.getSqlMap().commitTransaction();
			result = true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = false;
		} finally {
			SqlMapTool.getSqlMap().endTransaction();
		}
		return result;
	}

	public static void main(String args[]) {
		UserDao ud = new UserDao();
		User user = new User();
		user.setUserName("QiuQiu0034");
		user.setPassword("密码");
		user.setFirstName("姓氏");
		user.setSecondName("名字");
		user.setSex("男");
		user.setEmail("dq0034@qq.com");
		user.setPhoto("照片");
		user.setAnswer1("答案一");
		user.setAnswer2("答案二");
		user.setAnswer3("答案三");
		user.setQuestion1("问题一");
		user.setQuestion2("问题二");
		user.setQuestion3("问题三");
		try {
			user.setUserId(ud.insert(user));
			System.out.println(user.getUserId());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}